extends Node

@export var experience_manager: Node#需要连接经验管理器
@export var upgrade_screen_scene: PackedScene
@export var number_of_upgrade := 3#拿取的能力个数

var current_upgrades = {}#当前已经获得的能力
var upgrade_pool: WeightedTable = WeightedTable.new()

var upgrade_axe = preload("res://资源/局内升级/axe.tres")
var upgrade_axe_damage = preload("res://资源/局内升级/axe_damage.tres")
var upgrade_sword_rate = preload("res://资源/局内升级/sword_rate.tres")
var upgrade_sword_damage = preload("res://资源/局内升级/sword_damage.tres")
var upgrade_player_speed = preload("res://资源/局内升级/player_speed.tres")

func _ready() -> void:
	experience_manager.level_up.connect(on_level_up)
	GameEvents.ability_get_axe.connect(on_ability_get_axe)
	upgrade_pool.add_item(upgrade_axe)
	upgrade_pool.add_item(upgrade_sword_rate)
	upgrade_pool.add_item(upgrade_sword_damage)
	upgrade_pool.add_item(upgrade_player_speed, 5)
	pass

#拿取N个能力
func pick_item() -> Array[AbilityUpgrade]:
	var items: Array[AbilityUpgrade] = []
	var array = upgrade_pool.pick_item(number_of_upgrade)
	for item in array:
		items.append(item)
	return items

#升级时拿取N个能力并实例化
func on_level_up(_current_level: int) -> void:
	var chosen_upgrades: Array[AbilityUpgrade] = pick_item()
	if chosen_upgrades.is_empty():
		return
	var upgrade_screen_instacne = upgrade_screen_scene.instantiate()
	self.add_child(upgrade_screen_instacne)
	upgrade_screen_instacne.set_ability_upgrades(chosen_upgrades as Array[AbilityUpgrade])
	upgrade_screen_instacne.upgrade_selected.connect(on_upgrade_selected)
	pass

#当获得斧子的能力后解锁斧子的相关升级
func on_ability_get_axe() -> void:
	upgrade_pool.add_item(upgrade_axe_damage)
	pass

#能力被选择后开始应用能力
func on_upgrade_selected(upgrade: AbilityUpgrade) -> void:
	apply_upgrade(upgrade)
	pass

#应用能力
func apply_upgrade(upgrade: AbilityUpgrade) -> void:
	var has_upgrade := current_upgrades.has(upgrade.id)
	if !has_upgrade:
		current_upgrades[upgrade.id] = {
			"resource":upgrade.id,
			"quantity":1
		}
	else:
		current_upgrades[upgrade.id]["quantity"] += 1
	if current_upgrades[upgrade.id]["quantity"] == upgrade.max_quantity:
		upgrade_pool.remove_item(upgrade)
	GameEvents.emit_ability_upgrade_added(upgrade, current_upgrades)
	pass
